package P42;

import java.util.Scanner;

/**
 * @Author DJ同学
 * @Date 2021/3/4 23:57
 * @Version 1.0
 * @Name 接雨水
 * @problem https://leetcode-cn.com/problems/trapping-rain-water/?utm_source=LCUS&utm_medium=ip_redirect&utm_campaign=transfer2china
 */
public class Solution {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] num =  new int[n];
        for(int i = 0;i<n;i++){
            num[i] = scanner.nextInt();
        }
        long trap = trap(num);
        System.out.println(trap);
    }

    public static long trap(int[] height) {
        if(height==null||height.length<3){
            return 0;
        }
        int maxIndex = 0;
        //找到最大的版
        for(int i = 1;i<height.length;i++){
            if(height[i]>height[maxIndex]){
                maxIndex=i;
            }
        }
        int res = 0;
        int leftMax = height[0];
        for(int i = 1;i<maxIndex;i++){
            if(leftMax<height[i]){
                leftMax = height[i];
            }else{
                res+=leftMax-height[i];
            }
        }
        int rightMax = height[height.length-1];
        if(height.length-2>=0){
            for(int i = height.length-2;i>maxIndex;i--){
                if(rightMax<height[i]){
                    rightMax = height[i];
                }else{
                    res+=rightMax-height[i];
                }
            }
        }
        return res;
    }
}
